package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import model.TExaminationPaper;
import model.TExaminationPaperContent;
import model.TOption;
import model.TScaleTitleType;
import model.VTitle;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import persistent.factory.DAOFactory;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;
import util.toolkit.TimeUtil;

/**
 * 量表信息处理类
 * @author 徐震霖
 * @since 2019-02-25
 */
@Controller
@RequestMapping(value = "/examinationpaper")
public class SysExaminationPaperManagementController {

	/**
	 * 量表信息获取处理类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 量表信息获取处理类
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "量表信息获取",
			operationClassPath = "controller.SysExaminationPaperManagementController.getExaminationPaper(Model model, HttpServletRequest req,HttpServletResponse resp)",
			operationMenu = "量表组卷管理/量表信息添加组卷")
	@RequestMapping(value = "/getexaminationpaper")
	public String getExaminationPaper(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		int currentPage = 1;
		int pageSize = 10;

		try {
			String limit = req.getParameter("limit");
			String page = req.getParameter("page");
			String paperName = req.getParameter("papername");
			if (page != null && !page.equals("")) {
				currentPage = Integer.parseInt(page);
			}
			if (limit != null && !limit.equals("")) {
				pageSize = Integer.parseInt(limit);
			}
			if (paperName != null && !paperName.equals("")) {
				exp.andLike("paperName", paperName, String.class);
			}
			List<TExaminationPaper> listsize = DAOFactory.getIIExaminationPaperDAO().getPapers(exp.toString());
			List<TExaminationPaper> list = DAOFactory.getIIExaminationPaperDAO().getPapersByPage(exp.toString(),
					currentPage, pageSize);
			if (list != null && list.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", listsize.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "未获取到量表信息！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "出现异常，量表信息获取失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
	
	/**
	 * 量表题目信息获取处理类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 量表题目信息获取处理类
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "量表题目信息获取",
			operationClassPath = "controller.SysExaminationPaperManagementController.getExaminationPaperContent(Model model, HttpServletRequest req,HttpServletResponse resp)",
			operationMenu = "量表组卷管理/量表信息添加组卷")
	@RequestMapping(value="/getexaminationpapercontent")
	public String getExaminationPaperContent(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();
		
		try {
			String paperid = req.getParameter("paperid");
			if (paperid != null && !paperid.equals("") && !paperid.equals("0")) {
				exp.andEqu("paperid", paperid, Integer.class);
				List<TExaminationPaperContent> list = 
						DAOFactory.getIIExaminationPaperDAO().getContents(exp.toString());
				if (list != null && list.size() > 0) {
					result.put("code", 0);
					result.put("msg", "查询成功");
					result.put("count", list.size());
					JSONArray jsonArray = JSONArray.fromObject(list);
					result.element("data", jsonArray);
				}
				else {
					result.put("code", 1);
					result.put("msg", "未获取到题目信息！");
				}
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "量表编号不能为空，题目信息获取失败，请重试！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "出现异常，题目信息获取失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
	
	/**
	 * 量表信息添加处理类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 量表信息添加处理类
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个量表信息",
			operationClassPath = "controller.SysExaminationPaperManagementController.addExaminationPaper(Model model, HttpServletRequest req,HttpServletResponse resp)",
			operationMenu = "量表组卷管理/量表信息添加组卷")
	@RequestMapping(value="/addexaminationpaper")
	public String addExaminationPaper(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TimeUtil time = new TimeUtil();

		try {
			String paperName = req.getParameter("papername");    //试卷名称
			String paperDescribe = req.getParameter("paperdescribe");   //试卷描述
			//TODO 2019-03-18 09:01徐震霖修改开始
			//String usageType = req.getParameter("usagetype");    //使用类型
			//TODO 2019-03-18 09:01徐震霖修改结束
			String usageLevel=req.getParameter("usageLevel");    //使用等级
			
			String scaleTitleTypeid = req.getParameter("scaletitletypeid");

			if (paperName != null && !paperName.equals("") && paperDescribe != null && !paperDescribe.equals("")
				&& scaleTitleTypeid != null && !scaleTitleTypeid.equals("")) {

				TExaminationPaper paper = new TExaminationPaper();
				paper.setCreateTime(time.toTimestamp(new Date()).toString());
				//TODO 2019-03-18 09:01徐震霖修改开始
				paper.setPaperDescribe(paperDescribe);
				//TODO 2019-03-18 09:01徐震霖修改结束
				paper.setPaperName(paperName);
				paper.setUsageType(Constant.BACK_PAPER);
				paper.setUsageLevel(usageLevel);

				String scaleTitleTypeids[] = scaleTitleTypeid.split(Constant.STRING_SPLIT_OPTION);
				List<TExaminationPaperContent> contents = new ArrayList<TExaminationPaperContent>();
				for (int i = 0; i < scaleTitleTypeids.length; i++) {

					Expression expression = new Expression();
					expression.andEqu("scaleTitleTypeid", Integer.parseInt(scaleTitleTypeids[i]), Integer.class);
					List<VTitle> titlelist = DAOFactory.getITitleDAO().getTitles(expression.toString());
					for (VTitle tTitle : titlelist) {

						TExaminationPaperContent paperContent = new TExaminationPaperContent();
						TScaleTitleType scaleTitleType = 
								DAOFactory.getIScaleTitleTypeDAO().getTScaleTitleType(Integer.parseInt(scaleTitleTypeids[i]));					
						paperContent.setScaleTitleTypeid(scaleTitleType.getId());
						paperContent.setScaleTitleTypeName(scaleTitleType.getName());
						paperContent.setScaleTitleTypeDescribe(scaleTitleType.getDescribe());
						paperContent.setTitleid(tTitle.getTitleid());
						paperContent.setTitleDescribe(tTitle.getTitleDescribe());
						paperContent.setTitleName(tTitle.getTitleName());
						paperContent.setTitleNumber(tTitle.getTitleNumber());
						paperContent.setTitlePhonePath(tTitle.getTitlePhonePath());
						paperContent.setTitleType(tTitle.getTitleType());
						paperContent.setOptionNumber(tTitle.getOptionNumber());

						String optionContent = "";

						Expression exp = new Expression();
						exp.andEqu("titleid", tTitle.getTitleid(), String.class);
						exp.orderByAsc("optionNumber");
						List<TOption> optionlist = DAOFactory.getITitleDAO().getOptions(exp.toString());
						for (TOption tOption : optionlist) {
							optionContent += tOption.getOptionContent() + Constant.STRING_SPLIT_OPTION
									+ tOption.getOptionScore() + Constant.STRING_SPLIT;
						}
						paperContent.setOptionContent(optionContent);
						contents.add(paperContent);
					}
				}
				if (DAOFactory.getIIExaminationPaperDAO().addPaper(paper, contents)) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "量表信息添加成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "出现错误，量表信息添加失败，请重试！");
				}
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "必填项不能为空，量表信息添加失败！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现异常，量表信息添加失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
	
	/**
	 * 删除一个量表信息处理类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 删除一个量表信息处理类
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个量表信息",
			operationClassPath = "controller.SysExaminationPaperManagementController.deleteExaminationPaper(Model model, HttpServletRequest req,HttpServletResponse resp)",
			operationMenu = "量表组卷管理/量表信息添加组卷")
	@RequestMapping(value="/deleteexaminationpaper")
	public String deleteExaminationPaper(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		
		try {
			String paperid = req.getParameter("paperid");
			if (paperid != null && !paperid.equals("") && !paperid.equals("0")) {
				if(DAOFactory.getIIExaminationPaperDAO().deletePaper(Integer.parseInt(paperid))){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "量表信息删除成功！");
				}
				else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "出现错误，量表信息删除失败！");
				}
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "必填项不能为空，量表信息删除失败！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现异常，量表信息删除失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
}
